package com.ruoyi.common.utils;

/**
 * 地图工具类
 */
public class MapUtils {
    /**
     * 地面周长常量，单位公里
     */
    private static int EARTH_D = 40076;


    /**
     *  地球平均半径
     */
    private static final double EARTH_RADIUS = 6378137;

    /**
     * 维度间距常量，单位公里
     */
    private static double LAT_SPACE = 111.322;


    /**
     * 输入经纬度，和搜索半径
     * 输出x1,y1,x2,y2
     * 0:lat1
     * 1:lat2
     * 2:lon1
     * 3:lon2
     */
    public static double[] getLonAndLat(double lon,double lat,double space){
        double[] arr = new double[4];
        arr[2] = lat - (space / LAT_SPACE);
        arr[3] = lat + (space / LAT_SPACE);

        double cos = Math.cos(lat);
        double v = LAT_SPACE * cos;     //当前维度，每度经度的距离
        arr[0] = lon - (Math.abs(space / v));
        arr[1] = lon + (Math.abs(space / v));

        return arr;
    }

    /**
     * 输入经纬度
     * 输出x1,y1,x2,y2
     * 0:lat1
     * 1:lat2
     * 2:lon1
     * 3:lon2
     */
    public static double[] getLonAndLat(double lon,double lat){
        //默认搜索半径为50km
        return getLonAndLat(lon,lat,100);
    }

    /**
     * 输入定位坐标和店铺坐标
     * 输出店铺距离,单位米
     * @param lon
     * @param lat
     * @param shop_lon
     * @param shop_lat
     * @return
     */
    public static double getDistance(double lon,double lat,double shop_lon,double shop_lat){
        double radLat1 = rad(lat);
        double radLat2 = rad(shop_lat);
        double a = radLat1 - radLat2;
        double b = rad(lon) - rad(shop_lon);

        double s = 2 * Math.asin(
                Math.sqrt(
                        Math.pow(Math.sin(a/2),2)
                                + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)
                )
        );
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    //把经纬度转为度（°）
    private static double rad(double d){
        return d * Math.PI / 180.0;
    }
}
